package cn.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class SendMessageToClient extends Thread {
	private CharsetEncoder encoder = Charset.forName("utf-8").newEncoder();

	public void run() {
		if (DAServerSocketChannel.msgList.isEmpty()) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			String msg = (String) DAServerSocketChannel.msgList.removeFirst();
			sendMessage(msg);
		}
	}

	private void sendMessage(String msg) {
		String type = msg.substring(4);
		switch (Integer.parseInt(type)) {
		case 1:
			break;
		case 2:
			sendToClient(msg);
			break;
		default:
			break;
		}
	}

	private void sendToClient(String msg) {
		System.out.println("in sendToClient: " + msg);
		SocketChannel toChannel = DAServerSocketChannel.userHash.get(msg
				.substring(4, 11));// get to client channel
		ByteBuffer block = null;
		try {
			block = encoder.encode(CharBuffer.wrap(msg));
			toChannel.write(block);
		} catch (CharacterCodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			block.clear();
		}
	}
}